package com.helpdesk.controllers;

import com.helpdesk.beans.ComplaintsFacade;
import com.helpdesk.beans.ComplaintsLazyModel;
import com.helpdesk.controllers.util.JsfUtil;
import com.helpdesk.controllers.util.Mailer;
import com.helpdesk.controllers.util.PaginationHelper;
import com.helpdesk.controllers.util.TabBean;
import com.helpdesk.entities.Accounts;
import com.helpdesk.entities.Complaints;
import com.helpdesk.entities.HelpDeskEnums;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean(name = "complaintsController")
@SessionScoped
public class ComplaintsController implements Serializable {

    private Complaints current;
    private DataModel items = null;
    private LazyDataModel<Complaints> complaints;
    private LazyDataModel<Complaints> yourComplaints;
    private List<TabBean<Complaints>> tabs;
    @EJB
    private com.helpdesk.beans.ComplaintsFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private Complaints[] selected_complaints;
    private Accounts accountSelected;

    public ComplaintsController() {
    }

    /**
     * Get Item is selected
     *
     * @return
     */
    public Complaints getSelected() {
        if (current == null) {
            current = new Complaints();
            selectedItemIndex = -1;
        }
        return current;
    }

    /**
     * Set item selected
     *
     * @param complaint
     */
    public void setSelected(Complaints complaint) {
        current = complaint;
    }

    /**
     * get Complaints selected
     *
     * @return
     */
    public Complaints[] getSelected_complaints() {
        return selected_complaints;
    }

    public Accounts getAccountSelected() {
        return accountSelected;
    }

    public void setAccountSelected(Accounts accountSelected) {
        this.accountSelected = accountSelected;
    }

    /**
     * set Complaints selected
     *
     * @param selected_complaints
     */
    public void setSelected_complaints(Complaints[] selected_complaints) {
        this.selected_complaints = selected_complaints;
    }

    /**
     * get all complaints list
     *
     * @return
     */
    public LazyDataModel<Complaints> getComplaints() {
        if (complaints == null) {
            complaints = new ComplaintsLazyModel(getFacade().findAll());
        }
        return complaints;
    }

    /**
     * get complaints list of current user
     *
     * @return
     */
    public LazyDataModel<Complaints> getYourComplaints() {
        if (yourComplaints == null) {
            HttpSession session = JsfUtil.getSession(true);
            Accounts c = (Accounts) session.getAttribute(LoginController.currentUserKey);
            yourComplaints = new ComplaintsLazyModel(c.getCreatedComplaintsList());
        }
        return yourComplaints;
    }

    public List<TabBean<Complaints>> getTabs() {
        if (tabs == null) {
            tabs = new ArrayList<TabBean<Complaints>>();
            TabBean tab = new TabBean(getComplaints(), "All complaints");
            TabBean tab2 = new TabBean(getYourComplaints(), "Your Complaints");
            tabs.add(tab);
            tabs.add(tab2);
        }
        return tabs;
    }

    /**
     * get EJB facade for comunication with db
     *
     * @return
     */
    private ComplaintsFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        recreateModel();
        return "list";
    }

    public String prepareView() {
        if (current == null) {
            return "not_found";
        }
        return "view";
    }

    public String prepareCreate() {
        current = new Complaints();
        //selectedItemIndex = -1;
        return "new";
    }

    public String create() {
        try {
            HttpSession session = JsfUtil.getSession(true);
            Accounts acc = (Accounts) session.getAttribute(LoginController.currentUserKey);
            Date now = new Date();
            current.setDateCreated(now);
            current.setReporter(acc);
            current.setStatus(HelpDeskEnums.ComplaintStatus.NEW);
            current.setLastUpdated(now);
            getFacade().create(current);
            JsfUtil.addSuccessMessage("Complaint was created!");
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Complaint creation not succcess!");
            return null;
        }
    }

    public String prepareEdit() {
        if (current == null) {
            JsfUtil.addErrorMessage("No complaints is selected");
            return "not_found";
        }
        return "edit";
    }

    /**
     * Update current complaint
     *
     * @return
     */
    public String update() {
        try {
            if (current == null) {
                return "not_found";
            }
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("Complaint was updated");
            return "view_complaint";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Error");
            return null;
        }
    }

    /**
     * Destroy current user
     *
     * @return
     */
    public String destroy() {
        if (current == null) {
            JsfUtil.addErrorMessage("No complaints is selected");
            return "";
        }
        performDestroy();
        recreateModel();
        return "List";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ComplaintsDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void recreateModel() {
        tabs = null;
        complaints = null;
        yourComplaints = null;
    }

    public void preRenderView() {
        recreateModel();
    }

    public void assignTo() {
        try {
            if (selected_complaints != null && selected_complaints.length > 0 && accountSelected != null) {
                StringBuilder link_area_builder = new StringBuilder();
                for (Complaints complaint : selected_complaints) {
                    
                            
                            //"<br/> <a href='http://localhost:8080/techman/complaint/view.html?id=" + complaint.getId() + "'>" + complaint.getTitle() + "</a>";
                    complaint.setAssignedTo(accountSelected);
                }
                JsfUtil.addSuccessMessage("Assign success!");

                String mailMessage = "<html>"
                        + "<body>"
                        + "<h1> You have new complaint to resolve </h1>"
                        + "Follow this link: " + "http://localhost:8080/techman/complaint/view.html?id="
                        + "</body>"
                        + "</html>";
                Mailer mailer = new Mailer("no-reply@helpdesk.com", accountSelected.getEmail(), "New complaint was assigned to you", "");
            } else {
                JsfUtil.addWarnMessage("You must select complaint");
            }

        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Assign not success");
        }
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Complaints.class)
    public static class ComplaintsControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ComplaintsController controller = (ComplaintsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "complaintsController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Complaints) {
                Complaints o = (Complaints) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Complaints.class.getName());
            }
        }
    }
}
